/**
 * 设备工单粗排(产量) V1.00
 */
 function cp_man() {
    /**
     * 数组去重
     **/
    Array.prototype.distinct = function () {
        var arr = this, result = [], i, j, len = arr.length;
        for (i = 0; i < len; i++) {
            for (j = i + 1; j < len; j++) {
                if (arr[i] === arr[j]) {
                    j = ++i;
                }
            }
            result.push(arr[i]);
        }
        return result;
    }
    /**
     * Jsong数据分组排序
    */
    function JsonArrayGroup(arr) {
        let map = {}, dest = [], date_ary = {};
        for (let i = 0; i < arr.length; i++) {
            var ai = arr[i];
            if (!map[ai.Resource_ID]) {
                dest.push({
                    Resource_ID: ai.Resource_ID,
                    Resource: ai.Resource,
                    data: []
                });
                map[ai.Resource_ID] = ai;
                date_ary = []
            } else {
                for (let j = 0; j < dest.length; j++) {
                    let dj = dest[j];
                    if (dj.Resource_ID == ai.Resource_ID) {
                        if (date_ary[ai.Date] == null) {
                            date_ary[ai.Date] = ai;
                            dj.data.push(ai);
                        }
                        break;
                    }
                }
            }
        }
        return dest;
    }
    /**
     * 给某个日期增加n天
    */
    function addDate(date, days) {
        if (days == undefined || days == '') {
            days = 1;
        }
        var date = new Date(date);
        date.setDate(date.getDate() + days);
        var month = date.getMonth() + 1;
        var day = date.getDate();
        return date.getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
    }
    // 日期月份/天的显示，如果是1位数，则在前面加上'0'
    function getFormatDate(arg) {
        if (arg == undefined || arg == '') {
            return '';
        }
        var re = arg + '';
        if (re.length < 2) {
            re = '0' + re;
        }
        return re;
    }
    /**
    * 筛选Json数据
    **/
    function filterData(data, filter) {
        return data.filter(item => {
            var isIn = true
            for (var key in filter) {
                if (filter[key].indexOf(item[key]) < 0) {
                    isIn = false
                    break
                }
            }
            return isIn
        })
    }
    function AssessmentOfCapacity(source, WIP_ID) {

        var WorkShopLine = getListWithMultParams("WorkShopLine", { WorkShopId: WIP_ID });

        var work_noid = WorkShopLine.length > 0 ? WorkShopLine[0].Work_Shift : '';
        if (work_noid == null || work_noid == "" || work_noid == undefined) {
            Alert('提示：', WIP_ID + '未设置班制！');
            return false;
        }
        var Effective_Time_Arr = BS_Work_Shift_Effective_Time.filter(function (p) {
            if (p.Work_Noid === work_noid) {
                if (p.Sign_No % 2 != 0) {
                    return p;
                }
            }
        });
        let w_shift = Work_Shift.filter(function (p) {
            if (p.Work_Noid === work_noid) {
                return p;
            }
        });
        let X_Source = source.filter(function (p) {
            if (p.Resource_ID == WIP_ID && p.GcdType == 4) {
                return p;
            }
        });
        console.log(X_Source);
        temp = []; bc_temp = [];
        var month = new Date().getMonth() + 1;
        var day = new Date().getDate();
        var str = new Date().getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
        let myDate = JSON.stringify(str);
        var count = 0, bc = 0;
        foreach(source, function (item, i) {
            if (item.Resource_ID == WIP_ID) {
                if (Effective_Time_Arr.length > 0) {
                    if (item.Lock == 1) { return; }
                    if (temp[JSON.parse(myDate)] == null) {
                        temp[JSON.parse(myDate)] = item.PlanQty;
                        count++;
                        day_cout_ary[item.Resource] = count;
                    } else {
                        temp[JSON.parse(myDate)] += item.PlanQty;
                    }
                    let el = Effective_Time_Arr[bc];
                    var bcmc = el.BcType;
                    bcmc = myDate + bcmc;
                    if (bc_temp[bcmc] == null) {
                        bc_temp[bcmc] = item.PlanQty
                    } else {
                        bc_temp[bcmc] += item.PlanQty;
                    }
                    foreach(lockStore.getData().items, function (p) {
                        let __el = p.data;
                        let month = new Date(__el.Date).getMonth() + 1;
                        let day = new Date(__el.Date).getDate();
                        let str = new Date(__el.Date).getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
                        if (__el.Resource_ID == WIP_ID && myDate.replace(/\"/g, "") == str && __el.Scheduling == el.BcType && __el.Lock == 1) {
                            if (bc + 1 == w_shift[0].Work_Type) {
                                myDate = JSON.stringify(addDate(myDate.substring(1, myDate.length - 1), 1));
                                bc = 0;
                                temp = [];
                                bc_temp = [];
                            } else {
                                bc = bc + 1;
                                el = Effective_Time_Arr[bc];
                            }
                        }
                    });
                    let X_GDS = X_Source.filter(function (p) {
                        if (p.Resource_ID == WIP_ID && p.Scheduling == el.BcType && p.Date.getTime() == new Date(myDate).getTime()) {
                            return p;
                        }
                    });
                    let __X = 0;
                    if (X_GDS.length > 0) {
                        __X = X_GDS[0].PlanQty;
                    }
                    if (temp[JSON.parse(myDate)] > (WorkShopLine[0].DayProductionCapacity - __X)) {
                        if (item.GcdType != 4 && item.Lock == 0) {
                            item.Date = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                            item.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                            item.Scheduling = el.BcType;
                            item.index = i;
                            myDate = JSON.stringify(addDate(myDate.substring(1, myDate.length - 1), 1));
                            temp = [];
                            bc_temp = [];
                            bc = 0;
                        }
                    } else {
                        if (bc_temp[bcmc] > (el.Capacity - __X)) {
                            if (bc == Effective_Time_Arr.length - 1) {
                                if (item.GcdType != 4 && item.Lock == 0) {
                                    myDate = JSON.stringify(addDate(myDate.substring(1, myDate.length - 1), 1));
                                    item.Date = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                    item.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                    item.Scheduling = el.BcType;
                                    item.index = i;
                                    temp = [];
                                    bc_temp = [];
                                    bc = 0;
                                }
                            } else {
                                if (item.GcdType != 4 && item.Lock == 0) {
                                    item.Scheduling = el.BcType;
                                    item.Date = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                    item.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                    item.index = i;
                                    bc = bc + 1;
                                }
                            }
                        } else {
                            if (item.GcdType != 4 && item.Lock == 0) {
                                item.Scheduling = el.BcType;
                                item.Date = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                item.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(new Date(myDate).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                item.index = i;
                            }
                        }
                    }
                }
            }
        });
        return source;
    }
    function LockGcd(source) {
        let temp = [];
        let flg = false;
        foreach(lockStore.getData().items, function (el) {
            let item = el.data;
            if (item.Resource_ID == "" || item.Date == "" || item.Scheduling == "") {
                let row = item.id;
                var j = row.substring(row.indexOf('-') + 1, row.length);
                Alert('提示：', "第" + j + "行有空数据");
            } else {
                let filter = {
                    Resource_ID: [item.Resource_ID],
                    Date: [item.Date],
                    Scheduling: [item.Scheduling],
                }
                let _row = filterData(temp, filter);
                if (_row.length > 0) {
                    Alert('提示：', "不能有重复数据");
                } else {
                    temp.push({
                        Resource_ID: item.Resource_ID,
                        Date: item.Date,
                        Scheduling: item.Scheduling,
                    });
                    foreach(source, function (el) {
                        var d = new Date(el.Date).format('yyyy/MM/dd');
                        if (el.Resource_ID == item.Resource_ID && d == item.Date.format('yyyy/MM/dd') && el.Scheduling == item.Scheduling) {
                            el.Lock = item.Lock;
                            flg = true;
                        }
                    });
                }
            }
        });
        theGrid.collectionView.refresh();
        return flg;
    }
    /**
     * 班次内砂型排序
     * ary_date, cv, WIP_ID
     **/
    function SandSortingByShift(ary_date, cv, WIP_ID) {
        let bc_temp = [];
        var WorkShopLine = getListWithMultParams("WorkShopLine", { WorkShopId: WIP_ID });
        var work_noid = WorkShopLine.length > 0 ? WorkShopLine[0].Work_Shift : '';
        if (work_noid == null || work_noid == "" || work_noid == undefined) {
            Alert('提示：', WIP_ID + '未设置班制！');
            return false;
        }
        var Effective_Time_Arr = BS_Work_Shift_Effective_Time.filter(function (p) {
            return p.Work_Noid === work_noid;
        });
        let Temp = [];
        foreach(ary_date.split(','), function (ary) {
            let a = [];
            foreach(cv, function (p) {
                let d = new Date(p.Date).format('yyyy/MM/dd');
                if (d == ary && p.Resource_ID == WIP_ID) {
                    if (p.Number != null && p.Number != "" && p.GcdType == 0) {
                        //Temp.push();
                        a.push(p);
                        return p;
                    }
                }
            });
            Temp.push({
                d: ary,
                items: a
            });
        });
        foreach(Temp, function (el) {
            el.items.sort((a, b) => b.SandTypeId.localeCompare(a.SandTypeId));
            console.log(el.items);
            let bc = 0;
            foreach(el.items, function (cl, i) {
                if (cl.Resource_ID == WIP_ID) {
                    if (Effective_Time_Arr.length > 0) {
                        let el = Effective_Time_Arr[bc];
                        var bcmc = el.BcType;
                        bc_temp[bcmc] == null ? bc_temp[bcmc] = cl.PlanQty : bc_temp[bcmc] += cl.PlanQty;
                        if (bc_temp[bcmc] < el.Capacity) {
                            cl.Scheduling = bcmc;
                            cl.index = i;
                            cv.filter(function (p) {
                                if (p.Number == cl.Number) {
                                    return p = cl;
                                }
                            });
                        }
                        if (bc_temp[bcmc] > el.Capacity) {
                            cl.Scheduling = bcmc;
                            cl.index = i;
                            cv.filter(function (p) {
                                if (p.Number == cl.Number) {
                                    return p = cl;
                                }
                            });
                            bc = bc + 1;
                        }
                    }
                }
            });
            bc_temp = [];
        });
    }
    /**
     * 砂型排序后分摊
     * ary_date, cv, WIP_ID
     **/
    function SandSorting(ary_date, cv, WIP_ID) {
        let Temp = [];
        foreach(ary_date.split(','), function (ary) {
            foreach(cv, function (p) {
                let d = new Date(p.Date).format('yyyy/MM/dd');
                if (d == ary && p.Resource_ID == WIP_ID) {
                    if (p.Number != null && p.Number != "" && p.GcdType == 0) {
                        Temp.push(p);
                        return p;
                    }
                }
            });
        });
        Temp.sort((a, b) => b.SandTypeId.localeCompare(a.SandTypeId));
        Temp = AssessmentOfCapacity(Temp, WIP_ID);
        foreach(Temp, function (el) {
            cv.filter(function (p) {
                if (p.Number == el.Number) {
                    p = el;
                    return p;
                }
            });
        });
    }
    var id = "cuscomp-" + randNumber();
    var data = [];
    let lockStore = Ext.create('Ext.data.Store', {
        fields: ['Resource_ID', 'Date', 'Scheduling'],
        data: []
    });
    var ResourceIndex = [], Work_Shift, BS_Work_Shift_Effective_Time,
        LocaltblItem, AllSettings, WorkShopLine, Gcd_List;
    /*
    * @FactoryCalendar    加载工厂日历数据
    * @Work_Shift   加载班制表数据
    * @BS_Work_Shift_Effective_Time  加载班制明细表数据
    * @LocaltblItem  加载班次数据
    * @AllSettings  加载全览表数据
    * @TblEquWashTime 加载洗机工单数据
    * @WorkShopLine 加载车间档案数据
    * @Gcd_List  加载工单列表数据
    */
    function sourceData() {
        Work_Shift = getListWithMultParams("Work_Shift", { Work_Noid: '' });
        BS_Work_Shift_Effective_Time = getListWithMultParams("BS_Work_Shift_Effective_Time", { Work_Noid: '' });
        LocaltblItem = getListWithMultParams("LocaltblItem", { Ftype: 'Work_Classes' });
        AllSettings = getListWithMultParams("Inventory", {});
        //TblEquWashTime = getListWithMultParams("TblEquWashTime", {});
        WorkShopLine = getListWithMultParams("WorkShopLine", { WorkShopId: '' });
        //Gcd_List = getListWithMultParams("Material_Issue_Plan", { Type: 1, Closed: 0 });
    }
    sourceData();

    var day_cout_ary = [];
    /***
     * 统计产线天数
     * */
    function getResDayCount() {
        var day_ary = [], day_cout = [], count = 0;
        var source = theGrid.itemsSource.items;
        foreach(source, function (item) {
            if (day_ary[item.Date] == null) {
                day_ary[item.Date] = item.PlanQty;
                count++;
                day_cout[item.Resource] = count;
            } else {
                day_ary[item.Date] += item.PlanQty;
            }
        });
        return day_cout;
    }
    var theGrid;
    /**
     * 字段加载下拉数据
     **/
    function CreateDataMap(ary, column) {
        let ActionsMap = getTop().newObject("wijmo.grid.DataMap", [ary, "id", "name"]);
        theGrid.columns.getColumn(column).dataMap = ActionsMap;
    }

    Ext.onReady(function () {
        var comp = Ext.get(id);
        var dom = comp.el.dom;
        var groupcolmn = getTop().newObject("wijmo.collections.CollectionView", [data, {
            groupDescriptions: ['ParentID', 'Resource', 'Date', 'Scheduling'],
            sortDescriptions: ['Date', 'Resource_index', 'Scheduling', 'index']
        }]);
        //创建flexgrid表格对象
        theGrid = new getTop().newObject("wijmo.grid.FlexGrid", [dom, {
            //allowSorting: false,
            showSort: true,
            allowSorting: false,
            autoGenerateColumns: false,
            headersVisibility: 'Column',
            selectionMode: 5,
            frozenColumns: 6,
            columns: [
                { binding: 'index', header: '序号', minWidth: 80, allowSorting: false, isReadOnly: true },
                { binding: 'ParentID', header: '车间', width: 130, isReadOnly: true, visible: false, allowDragging: false },
                { binding: 'Resource_ID', header: '设备', width: 130, visible: false, allowDragging: false },
                { binding: 'Resource_index', header: '设备序号', width: 130, visible: false, allowDragging: false },
                { binding: 'Resource', header: '设备', width: 130 },
                { binding: 'Date', header: '日期', width: 90, dataType: 'Date', format: 'd', allowDragging: false, visible: true, allowSorting: false },
                { binding: 'GcdType', header: '工单类型', isReadOnly: true, width: 5, visible: true, allowSorting: false, allowDragging: false },
                { binding: 'PlanDateStart', header: 't计开', width: 83, dataType: 'Date', format: 'd', isReadOnly: true, format: 'd', visible: true, allowSorting: false, allowDragging: false },
                { binding: 'ScheduleDateDifference', header: 'ΔT计排', width: 75, isReadOnly: true, format: 'd', allowSorting: false, allowDragging: false },
                { binding: 'Scheduling', header: '班次', width: 80 },
                { binding: 'SaOrderKey', header: '急', width: 60 },
                { binding: 'CustomerKey', header: 'V', width: 50, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'Matching_icon', header: '齐', width: 30, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'Matching', header: '齐', width: 30, isReadOnly: true, visible: false, allowSorting: false, allowDragging: false },
                { binding: 'Lock', header: '锁定', width: 80 },
                { binding: 'Number', header: '工单', width: 106, isReadOnly: false, allowSorting: false, allowDragging: false },
                { binding: 'FStatus', header: '工单状态', width: 65, visible: false, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'Inventory_ID', header: '物料编码', width: 110, isReadOnly: false, allowSorting: false, allowDragging: false },
                { binding: 'Description', header: '物料名称', width: 180, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'BatchNO', header: '批次号', width: 73, isReadOnly: false, allowSorting: false, allowDragging: false },
                { binding: 'PlanNpkg', header: '目标数量', width: 100, dataType: 'Number', isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'StdInventory_ID', header: '半成品编码', width: 110, isReadOnly: false, visible: true, allowSorting: false, allowDragging: false },
                { binding: 'MfgCatID', header: '砂型', width: 110, isReadOnly: true, visible: true, allowDragging: false },
                { binding: 'SandTypeId', header: '砂型编码', width: 110, visible: true, isReadOnly: true, allowDragging: false },
                { binding: 'Unit_Weight', header: '规格', width: 45, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'PlanQty', header: '计划产量', width: 71, dataType: 'Number', aggregate: 'Sum', isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'PlanDate', header: '∑T排', width: 53, dataType: 'Number', aggregate: 'Sum', isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: '日占有率', header: '日占有率', width: 69, isReadOnly: true, dataType: 'Number', aggregate: 'Sum', allowSorting: false, allowDragging: false },
                { binding: 'Summary', header: '备注', width: 110, isReadOnly: false, allowSorting: false, allowDragging: false },
                { binding: 'HCapacity', header: '小时产能', width: 71, isReadOnly: true, dataType: 'Number', allowSorting: false, allowDragging: false },
                { binding: '批占有率', header: '批占有率', width: 69, isReadOnly: true, dataType: 'Number', allowSorting: false, allowDragging: false },
                { binding: 'PlanDate', header: 'T计', width: 60, dataType: 'Number', isReadOnly: true, visible: true, allowSorting: false, allowDragging: false },
                { binding: 'ScheduleStartDate', header: 't排开', width: 83, dataType: 'Date', format: 'd', isReadOnly: false, format: 'd', allowSorting: false, allowDragging: false },
                { binding: 'ScheduleEndDate', header: 't排完', width: 79, isReadOnly: true, dataType: 'Date', format: 'd', allowSorting: false, allowDragging: false },
                { binding: 'PlanDateEnd', header: 't计完', width: 83, dataType: 'Date', format: 'd', isReadOnly: true, format: 'd', visible: true, allowSorting: false, allowDragging: false },
                { binding: '日产能 ', header: '日产能', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'OnePlanMAX', header: '批产能', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: '实际日占有率', header: '实际日占有率', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: '实际批占有率', header: '实际批占有率', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'ActDateStart ', header: 't实开', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'ActDateEnd', header: 't实完', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'ActDate', header: 'T实', width: 110, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'T计实差', header: 'ΔT计实', width: 65, isReadOnly: true, allowSorting: false, allowDragging: false },
                { binding: 'T排实', header: 'ΔT排实', width: 65, isReadOnly: true, format: 'd', allowSorting: false, allowDragging: false },
                { binding: '物料分类', header: '物料分类', isReadOnly: true, width: 90, allowSorting: false, allowDragging: false },
                { binding: 'apsno', header: '流水号', isReadOnly: true, width: 90, allowSorting: false, allowDragging: false },
            ],
            selectionChanged: function (s) {
                // setTimeout(function () {
                // 	s.startEditing(false);
                // }, 50);
            },
            beginningEdit: function (s, e) {
                var item = s.rows[e.row].dataItem;
                if (item.GcdType == 4) {
                    e.cancel = true;
                }
            },
            itemsSource: groupcolmn,
            cellEditEnding: function (s, e) {
                var col = s.columns[e.col];
                if (col.binding == 'Date') {
                    if (s.activeEditor.value != theGrid.getCellData(e.row, e.col)) {
                        theGrid.setCellData(e.row, "ScheduleStartDate", s.activeEditor.value);
                        theGrid.setCellData(e.row, "ScheduleEndDate", s.activeEditor.value);
                    }
                }
                if (col.binding == 'Resource') {
                    if (s.activeEditor.value != theGrid.getCellData(e.row, e.col)) {
                        theGrid.setCellData(e.row, "Resource_ID", s.activeEditor.value);
                    }
                }
            },
            refreshed: function () {
                let source = theGrid.itemsSource.items;
                let ary = [];
                let count = 0;
                for (let i = 0; i < source.length; i++) {
                    source[i].index = i;
                    if (ary[source[i].Resource] == null) {
                        ary[source[i].Resource] = count;
                        count++;
                    }
                    ResourceIndex.sort(function (a, b) { return a.Index - b.Index });
                    foreach(ResourceIndex, function (el) {
                        if (el.Resource_ID == source[i].Resource_ID) {
                            source[i].Resource_index = el.Index;
                        }
                    });
                }
            },
            updatedView: function () {
                btnMoveUpward.enable();
                btnMoveDown.enable();
            }
        }]);
        //启用列筛选过滤功能
        var filter = new getTop().newObject("wijmo.grid.filter.FlexGridFilter", [theGrid]);
        filter.defaultFilterType = getTop().wijmo.grid.filter.FilterType.Condition;
        filter.showSortButtons = false;
        //设置分组收缩级别
        theGrid.collapseGroupsToLevel(2);
        //启用wijmo表的列排序功能
        theGrid.sortingColumn.addHandler(function (s, e) {
            var view = s.collectionView, sds = view.sortDescriptions;
            e.cancel = true;
            if (e.data.ctrlKey) {
                sds.clear();
                return;
            }
            var prop = s.columns[e.col].binding, index = -1;
            for (var i = 0; i < sds.length && index < 0; i++) {
                if (sds[i].property == prop) {
                    index = i;
                }
            }
            if (index < 0) { // not found, add now
                var sd = new getTop().wijmo.collections.SortDescription(prop, true);
                sds.push(sd);
            }
            else { // found, flip its direction
                var sd = new getTop().wijmo.collections.SortDescription(prop, !sds[index].ascending);
                sds.splice(index, 1, sd);
            }
        });
        //获取FlexGrid选中行数据
        theGrid.getSelectItems = function () {
            let __ary = new Array();
            var rows = this.selectedItems;
            for (let index = 0; index < rows.length; index++) {
                const element = rows[index];
                if (!element.level && element.level != 0) {
                    __ary.push(rows[index]);
                }
            }
            return __ary;
        }
        //格式化wijmo表格列数据
        theGrid.formatItem.addHandler(function (s, e) {
            if (e.panel == s.topLeftCells) {
                e.cell.innerHTML = '<span class="column-picker-icon glyphicon glyphicon-cog"></span>';
            }
            if (e.panel == s.cells) {
                var col = s.columns[e.col];
                var group_level = e._p.rows[e.row].level;

                if (group_level == 1) {
                    var curFlexGridRow = theGrid.rows[e.row];
                    curFlexGridRow.cssClass = 'cell-resource';
                }
                if (col.binding == 'GcdType') {
                    if (group_level == undefined) {
                        var GcdType = s.getCellData(e.row, theGrid.getColumn("GcdType").index);
                        if (GcdType == 2) {
                            var curFlexGridRow = theGrid.rows[e.row];
                            curFlexGridRow.cssClass = 'cell-country';
                        }
                    }
                }
                if (col.binding == 'PlanDate') {
                    var PlanDate = s.getCellData(e.row, theGrid.getColumn("PlanDate").index);
                    var html = '<div style="color:{cls}"><span style="font-size:100%">{val}</span> ';
                    html = html.replace('{val}', PlanDate == undefined ? 0 : PlanDate.toFixed(2));
                    if (group_level == 2) {
                        if (PlanDate > 11) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                    if (group_level == 1) {
                        if (PlanDate > 22) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                    if (group_level == 0) {
                        if (PlanDate > 22) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                }
                if (col.binding == 'PlanQty') {
                    var diff = s.getCellData(e.row, theGrid.getColumn("PlanQty").index);
                    var Resource_ID;
                    var day_vount = getResDayCount()[e._p.rows[e.row].dataItem.name];
                    if (group_level == 1 || group_level == 2) {
                        Resource_ID = e._p.rows[e.row].dataItem.items[0].Resource_ID;
                    }
                    if (group_level == 3) {
                        Resource_ID = e._p.rows[e.row].dataItem.items[0].Resource_ID;
                    }
                    var daycn = WorkShopLine.filter(function (p) {
                        if (p.WorkShopId == Resource_ID) {
                            return p;
                        }
                    });
                    var cxn = daycn.length == 0 ? 0.001 : daycn[0].DayProductionCapacity;
                    var html = '<div style="color:{cls}"><span style="font-size:100%">{val}</span> ';
                    html = html.replace('{val}', diff == undefined ? 0 : diff.toFixed(2));
                    if (group_level == 3) {
                        if (diff > (cxn / 2)) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                    if (group_level == 2) {
                        if (diff > cxn) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                    if (group_level == 1) {
                        if (diff > (cxn * day_vount)) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                    if (group_level == 0) {
                        if (diff > (cxn * day_vount)) {
                            html = html.replace('{cls}', 'red');
                        }
                        e.cell.innerHTML = html;
                    }
                }
                if (col.binding == 'Matching_icon') {
                    var matching = s.getCellData(e.row, theGrid.getColumn("Matching").index);
                    var html = '<div style="color:{cls}"><span style="font-size:100%">&nbsp<i class="wj-glyph-{glyph}"></i></span> ';
                    if (matching == 1) {
                        html = html.replace('{cls}', 'green');
                        html = html.replace('{glyph}', 'circle');
                        e.cell.innerHTML = html;
                    }
                    if (matching == 0) {
                        html = html.replace('{cls}', 'red');
                        html = html.replace('{glyph}', 'circle');
                        e.cell.innerHTML = html;
                    }
                }
                if (col.binding == 'SaOrderKey') {
                    var saOrderKey = s.getCellData(e.row, theGrid.getColumn("SaOrderKey").index);
                    var html = '<input type="text" style="color:{cls};border:0;" value="{val}" /> ';
                    if (saOrderKey == 8) {
                        html = html.replace('{cls}', 'red');
                        html = html.replace('{val}', '急');
                    }
                    if (saOrderKey == 0) {
                        html = html.replace('{cls}', 'greed');
                        html = html.replace('{val}', '');
                    }
                }
                if (col.binding == '日占有率') {
                    var temp = s.getCellData(e.row, theGrid.getColumn("PlanQty").index);
                    var day_vount = getResDayCount()[e._p.rows[e.row].dataItem.name];
                    var Resource_ID;
                    if (group_level == 1 || group_level == 2) {
                        Resource_ID = e._p.rows[e.row].dataItem.items[0].Resource_ID;
                    }
                    var daycn = WorkShopLine.filter(function (p) {
                        if (p.WorkShopId == Resource_ID) {
                            return p;
                        }
                    });
                    var cxn = daycn.length == 0 ? 0.001 : daycn[0].DayProductionCapacity;
                    var html = '<div style="color:{cls}"><span style="font-size:100%">{val}%</span> ';
                    if (group_level == 0) {
                        html = html.replace('{val}', '');
                    } else if (group_level == 1) {
                        html = html.replace('{val}', parseInt(((temp) / cxn) * 100 / day_vount));
                    } else if (group_level == 2) {
                        html = html.replace('{val}', parseInt(((temp) / cxn) * 100));
                    } else {
                        html = html.replace('{val}', '');
                    }
                    e.cell.innerHTML = html;
                }
                if (col.binding == '批占有率') {
                    var html = '<div style="color:{cls}"><span style="font-size:100%">{val}%</span> ';
                    if (group_level == 0) {
                        html = html.replace('{val}', '');
                    } else if (group_level == 1) {
                        html = html.replace('{val}', '');
                    } else if (group_level == 2) {
                        html = html.replace('{val}', '');
                    } else if (group_level == 3) {
                        html = html.replace('{val}', '');
                    } else {
                        var temp = s.getCellData(e.row, theGrid.getColumn("PlanQty").index);
                        var invid = s.getCellData(e.row, theGrid.getColumn("Inventory_ID").index);
                        var allsettings = AllSettings.filter(function (p) {
                            if (p.Inventory_ID == invid) {
                                return p;
                            }
                        });
                        var OnePlanMAX = allsettings.length > 0 ? allsettings[0].OnePlanMAX : 1;
                        html = html.replace('{val}', parseInt((temp / OnePlanMAX) * 100));
                    }
                    e.cell.innerHTML = html;
                }
                if (col.binding == 'ScheduleDateDifference') {
                    var start = s.getCellData(e.row, theGrid.getColumn("PlanDateStart").index);
                    var temp2 = s.getCellData(e.row, theGrid.getColumn("ScheduleEndDate").index);
                    var html = '<div style="color:{cls}"><span style="font-size:100%">{val}</span> ';
                    html = html.replace('{val}', Math.round((new Date(start) - new Date(temp2)) / 1000 / 60 / 60 / 24));
                    e.cell.innerHTML = html;
                }
            }
        });
        //添加是否急单列下拉数据
        CreateDataMap([{ id: 8, name: '急' }, { id: 0, name: '否' }], "SaOrderKey");
        //添加班制列下拉数据
        let Scheduling_Map = [];
        foreach(LocaltblItem, function (el) {
            Scheduling_Map.push({ id: el.FCode, name: el.FDescript });
        });
        CreateDataMap(Scheduling_Map, "Scheduling");
        //添加是否锁定下拉数据
        CreateDataMap([{ id: 1, name: '已锁' }, { id: 0, name: '未锁' }], "Lock");
    });
    /**
     * 读取原计划
     * 读取当天以前的排产计划到当前排产界面
     * 
     * */
    let btnReadOldPlan = Ext.create('Ext.Button', {
        tooltip: '读取原计划',
        glyph: 0xf5ae,
        handler: function () {
            var source = theGrid.itemsSource.sourceCollection;
            getTopWindow().openWindow("原排产计划", "/ProductionPlanGcd?disble_operate_type=Add,Edit,Delete,Print,Record,BackRecord,Verify,Search&selectmode=true&Maker=" + getTopWindow().username + "&MakeDate<" + now,
                900, 600, function (v) {
                    if (v != null && typeof (v) == "object") {
                        if (v.length == 2) {
                            source.splice(0, source.length);
                            theGrid.collectionView.refresh();
                            var child_list = getListWithMultParams("ProductionPlanGcdDetail", { ProductionNo: v[1].ProductionNo });
                            child_list.sort(function (a, b) { return a.Noid - b.Noid });
                            let pid = child_list[0].WIP_ID;
                            let ary1 = [];
                            foreach(WorkShopLine, function (el) {
                                if (el.Parent_ID == pid) {
                                    let obj = new Object();
                                    obj.id = el.Description;
                                    obj.name = el.Description;
                                    ary1.push(obj);
                                }
                            });
                            CreateDataMap(ary1, "Resource");
                            Gcd_List = [];
                            Gcd_List = getListWithMultParams("Material_Issue_Plan_NFSAP", { Des_StockID: pid, Type: 1, Closed: 0 });
                            foreach(child_list, function (item) {
                                let nowDate = new Date().format('yyyy/MM/dd');
                                let gcd_temp = Gcd_List.filter(function (p) {
                                    if (p.NO == item.IssuleNo) {
                                        return p;
                                    }
                                });
                                if (item.IssuleNo == null || item.IssuleNo == "") {
                                    gcd_temp.length = 2;
                                }
                                if (gcd_temp.length > 0 || item.IssuleNo.indexOf("XGCD") == 0) {
                                    let ScheduleEndDate = new Date(item.ScheduleEndDate).format('yyyy/MM/dd');
                                    if (ScheduleEndDate >= nowDate) {
                                        var temp = WorkShopLine.filter(function (p) {
                                            if (item.Resource_ID == p.WorkShopId) {
                                                return p;
                                            }
                                        });
                                        var temp_allsetting = AllSettings.filter(function (p) {
                                            if (item.Inventory_id == p.Inventory_ID) {
                                                return p;
                                            }
                                        });
                                        var view = theGrid.collectionView;
                                        var newItem = view.addNew();

                                        newItem.Resource_ID = item.Resource_ID;
                                        newItem.Resource_index = item.Resource_index;
                                        newItem.Resource = temp.length > 0 ? temp[0].Description : '';
                                        newItem.ParentID = item.WIP_ID;
                                        newItem.Date = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
                                        switch (item.Scheduling) {
                                            case "白班":
                                                newItem.Scheduling = '001';
                                                break;
                                            case "夜班":
                                                newItem.Scheduling = '002';
                                                break;
                                            case "早班":
                                                newItem.Scheduling = '003';
                                                break;
                                            case "晚班":
                                                newItem.Scheduling = '004';
                                                break;
                                            default: newItem.Scheduling = item.Scheduling;
                                        }
                                        newItem.Inventory_ID = item.Inventory_id;
                                        newItem.Description = temp_allsetting.length > 0 ? temp_allsetting[0].Description : '';
                                        newItem.Number = item.IssuleNo;
                                        newItem.BatchNO = item.BatchNO;
                                        newItem.PlanQty = item.IssueQty;
                                        newItem.Lock = 0;
                                        newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.PbeginDate, 'yyyy/MM/dd');
                                        newItem.PlanDateEnd = getTop().wijmo.Globalize.parseDate(item.PEndDate, 'yyyy/MM/dd');
                                        newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.ScheduleStartDate, 'yyyy/MM/dd');
                                        newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
                                        newItem.PlanDate = item.MfgPlanTime;
                                        newItem.PlanNpkg = item.PlanNpkg;
                                        newItem.StdInventory_ID = item.StdInventory_ID;
                                        newItem.MfgCatID = item.MfgCatID;
                                        newItem.SandTypeId = temp_allsetting.length > 0 ? temp_allsetting[0].SandTypeId : '';
                                        newItem.HCapacity = item.HCapacity;
                                        newItem.Summary = item.Summary;
                                        newItem.Matching = item.Matching;
                                        newItem.SaOrderKey = item.SaOrderKey;
                                        newItem.ScheduleDateDifference = 0;
                                        newItem.GcdType = 0;
                                        newItem.FStatus = '';
                                        newItem.Capacity = temp_allsetting.length > 0 ? temp_allsetting[0].Capacity : '';
                                        newItem.OnePlanMAX = temp_allsetting.length > 0 ? temp_allsetting[0].OnePlanMAX : '';
                                        newItem.Unit_Weight = temp_allsetting.length > 0 ? temp_allsetting[0].Style : 1;
                                        view.commitNew();
                                    }
                                }
                            });
                        } else {
                            Alert('提示:', '只能选择一条数据！');
                        }
                    }
                });
        }
    });
    /***
     * 读当天计划
     * 读取当前的排产计划到当前的排产界面
     * */
    let btnReadNowPlan = Ext.create('Ext.Button', {
        tooltip: '读当天计划',
        glyph: 0xf0ce,
        handler: function () {
            var source = theGrid.itemsSource.sourceCollection;
            getTopWindow().openWindow("当天排产计划", "/ProductionPlanGcd?disble_operate_type=Add,Edit,Delete,Print,Record,BackRecord,Verify,Search&selectmode=true&Maker=" + getTopWindow().username + "&MakeDate=" + Common.formatDate(now, 'yyyy/MM/dd'),
                900, 600, function (v) {
                    if (v != null && typeof (v) == "object") {
                        if (v.length == 2) {
                            source.splice(0, source.length);
                            theGrid.collectionView.refresh();
                            var child_list = getListWithMultParams("ProductionPlanGcdDetail", { ProductionNo: v[1].ProductionNo });
                            child_list.sort(function (a, b) { return a.Noid - b.Noid });
                            let pid = child_list[0].WIP_ID;
                            let ary1 = [];
                            foreach(WorkShopLine, function (el) {
                                if (el.Parent_ID == pid) {
                                    let obj = new Object();
                                    obj.id = el.Description;
                                    obj.name = el.Description;
                                    ary1.push(obj);
                                }
                            });
                            CreateDataMap(ary1, "Resource");
                            Gcd_List = [];
                            Gcd_List = getListWithMultParams("Material_Issue_Plan_NFSAP", { Des_StockID: pid, Type: 1, Closed: 0 });
                            foreach(child_list, function (item) {
                                let gcd_temp = Gcd_List.filter(function (p) {
                                    if (p.NO == item.IssuleNo) {
                                        return p;
                                    }
                                });
                                if (item.IssuleNo == null || item.IssuleNo == "") {
                                    gcd_temp.length = 2;
                                }
                                if (gcd_temp.length > 0 || item.IssuleNo.indexOf("XGCD") == 0) {
                                    var temp = WorkShopLine.filter(function (p) {
                                        if (item.Resource_ID == p.WorkShopId) {
                                            return p;
                                        }
                                    });
                                    var temp_allsetting = AllSettings.filter(function (p) {
                                        if (item.Inventory_id == p.Inventory_ID) {
                                            return p;
                                        }
                                    });
                                    var view = theGrid.collectionView;
                                    var newItem = view.addNew();
                                    newItem.Resource_index = item.Resource_index;
                                    newItem.Resource_ID = item.Resource_ID;
                                    newItem.Resource = temp.length > 0 ? temp[0].Description : '';
                                    newItem.ParentID = item.WIP_ID;
                                    newItem.Date = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
                                    switch (item.Scheduling) {
                                        case "白班":
                                            newItem.Scheduling = '001';
                                            break;
                                        case "夜班":
                                            newItem.Scheduling = '002';
                                            break;
                                        case "早班":
                                            newItem.Scheduling = '003';
                                            break;
                                        case "晚班":
                                            newItem.Scheduling = '004';
                                            break;
                                        default: newItem.Scheduling = item.Scheduling;
                                    }
                                    newItem.Inventory_ID = item.Inventory_id;
                                    newItem.Description = temp_allsetting.length > 0 ? temp_allsetting[0].Description : '';
                                    newItem.Number = item.IssuleNo;
                                    newItem.BatchNO = item.BatchNO;
                                    newItem.PlanQty = item.IssueQty;
                                    newItem.Lock = 0;
                                    newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.PbeginDate, 'yyyy/MM/dd');
                                    newItem.PlanDateEnd = getTop().wijmo.Globalize.parseDate(item.PEndDate, 'yyyy/MM/dd');
                                    newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.ScheduleStartDate, 'yyyy/MM/dd');
                                    newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.ScheduleEndDate, 'yyyy/MM/dd');
                                    newItem.PlanDate = item.MfgPlanTime;
                                    newItem.PlanNpkg = item.PlanNpkg;
                                    newItem.StdInventory_ID = item.StdInventory_ID;
                                    newItem.MfgCatID = item.MfgCatID;
                                    newItem.SandTypeId = temp_allsetting.length > 0 ? temp_allsetting[0].SandTypeId : '';
                                    newItem.HCapacity = item.HCapacity;
                                    newItem.Summary = item.Summary;
                                    newItem.Matching = item.Matching;
                                    newItem.SaOrderKey = item.SaOrderKey;
                                    newItem.GcdType = 0;
                                    newItem.FStatus = '';
                                    newItem.Capacity = temp_allsetting.length > 0 ? temp_allsetting[0].Capacity : '';
                                    newItem.OnePlanMAX = temp_allsetting.length > 0 ? temp_allsetting[0].OnePlanMAX : '';
                                    newItem.Unit_Weight = temp_allsetting.length > 0 ? temp_allsetting[0].Style : 1;
                                    view.commitNew();
                                }
                            });
                        } else {
                            Alert('提示:', '只能选择一条数据！');
                        }
                    }
                });
        }
    });
    /***
     * 未清生产订单
     * 从工程单表中读取有效订单，压单的记录行背景色标记红色，将选择的工单写入到排产界面
     * */
    let btnNotFinishProductionOrder = Ext.create('Ext.Button', {
        tooltip: '未清生产订单',
        glyph: 0xf4ce,
        handler: function () {
            var rows = theGrid.selectedItems[0];
            var source = theGrid.itemsSource.items;
            var gd_arry = [];
            var cond = {
                t: "and", child: []
            }
            var ary1 = [];
            foreach(source, function (item, i) {
                if (rows.Resource_ID == item.Resource_ID) {
                    if (item.Number != null && item.Number != undefined && item.Number != "") {
                        gd_arry.push(item.Number);
                    }
                }
            });
            var list;
            var oneTbar = new Ext.Toolbar({
                items: [{
                    labelWidth: 30,
                    xtype: 'textfield',
                    name: 'WipId',
                    fieldLabel: '车间',
                    value: ''
                }, {
                    labelWidth: 60,
                    xtype: 'textfield',
                    name: 'WipId',
                    fieldLabel: '关键容器',
                    value: ''
                }, {
                    xtype: 'datefield',
                    name: 'plan_start',
                    fieldLabel: '计划工开时间起'
                }, {
                    xtype: 'datefield',
                    name: 'plan_end',
                    fieldLabel: '计划工开时间止'
                }, {
                    tooltip: '查询',
                    glyph: 0xf002,
                    handler: function () {

                    }
                }
                ]
            });
            function wnd(list, rows) {
                let filter_val = rows.length < 1 ? rows.Resource_ID : '';
                foreach(list, function (el) {
                    var inv = AllSettings.filter(function (p) {
                        if (p.Inventory_ID == el.Inventory_ID) {
                            return p;
                        }
                    });
                    el.Description = inv.length == 0 ? "" : inv[0].Description;
                });
                var store = Ext.create('Ext.data.Store', {
                    fields: ['Des_StockID', 'NO', 'BatchNO', 'JiHao', 'Inventory_ID', 'Description', 'CQty', 'WrkHrs', 'ReqDate', 'DuDate', 'CUST', 'Project', 'SelfMfg_OrdersPO', 'Date', 'IsProduceResIssuePlan'],
                    sortable: true,
                    sorters: [{ property: "ReqDate", direction: "ASC" }], //给定一个默认的排序方式      
                    data: list
                });
                foreach(gd_arry, function (c) {
                    let record = store.findExact('NO', c);
                    if (record > -1) {
                        store.removeAt(record);
                    }
                });
                var grid = getTop().Ext.create('Ext.grid.Panel', {
                    store: store,
                    region: 'south',
                    frame: false,
                    width: 900,
                    height: '100%',
                    viewConfig: {
                        columnLines: true,
                        stripeRows: true,
                        enableTextSelection: true,
                        animateShadow: true,
                        forceFit: true,
                        getRowClass: function (record) {
                            let nowDate = new Date().format('yyyy/MM/dd');
                            let tmdate = new Date(record.data.DuDate).format('yyyy/MM/dd');;
                            if (tmdate < nowDate) {
                                return "bglightred";
                            }
                        }
                    },
                    selModel: {
                        mode: 'MULTI',
                        checkboxSelect: true,
                        injectCheckbox: 1,
                        type: 'checkboxmodel'
                    },
                    plugins: {
                        gridfilters: true
                    },
                    columns: [
                        { header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true },
                        {
                            dataIndex: 'Des_StockID', header: '车间', width: 51, sortable: false, menuDisabled: false,
                            filter: {
                                type: 'string', itemDefaults: { emptyText: '查询...' }
                            }
                        },
                        {
                            dataIndex: 'NO', header: '工程单号', width: 109, sortable: false, menuDisabled: false,
                            filter: {
                                type: 'string'
                            }
                        },
                        {
                            dataIndex: 'JiHao', text: '查询', header: '关键容器', width: 87, sortable: false, menuDisabled: false,
                            filter: {
                                type: 'string', itemDefaults: { emptyText: '查询...' }, value: rows.Resource_ID
                            }
                        },
                        {
                            dataIndex: 'BatchNO', header: '批次号', width: 112, sortable: false, menuDisabled: false, filter: {
                                type: 'string'
                            }
                        },
                        {
                            dataIndex: 'LvWanAct', header: '半成品工单号', width: 112, sortable: false, menuDisabled: false, filter: {
                                type: 'string'
                            }
                        },
                        {
                            dataIndex: 'Inventory_ID', header: '成品', width: 112, sortable: false, menuDisabled: false, filter: {
                                type: 'string'
                            }
                        },
                        {
                            dataIndex: 'Description', header: '成品名称', width: 200, sortable: false, menuDisabled: false, filter: {
                                type: 'string'
                            }
                        },
                        {
                            dataIndex: 'CQty', header: '生产总量', width: 74, sortable: false, menuDisabled: false, filter: {
                                type: 'number'
                            }
                        },
                        {
                            dataIndex: 'WrkHrs', header: '总工时', width: 61, sortable: false, menuDisabled: false, filter: {
                                type: 'number'
                            }
                        },
                        {
                            dataIndex: 'ReqDate', header: '计划工开时间', width: 100, sortable: false, menuDisabled: false, filter: {
                                type: 'date'
                            }
                        },
                        {
                            dataIndex: 'DuDate', header: '要求完成时间', width: 100, sortable: false, menuDisabled: false, filter: {
                                type: 'date'
                            }
                        },
                        {
                            dataIndex: 'CUST', header: '客户编码', width: 74, sortable: false, menuDisabled: false, filter: {
                                type: 'number'
                            }
                        },
                        {
                            dataIndex: 'Project', header: '计划单号', width: 74, sortable: false, menuDisabled: false, filter: {
                                type: 'number'
                            }
                        },
                        {
                            dataIndex: 'SelfMfg_OrdersPO', header: '车间加工计划号', width: 100, sortable: false, menuDisabled: false, filter: {
                                type: 'number'
                            }
                        },
                        {
                            dataIndex: 'Date', header: '开单日期', width: 100, sortable: false, menuDisabled: false, filter: {
                                type: 'date'
                            }
                        },
                        {
                            dataIndex: 'IsProduceResIssuePlan', header: '排程状态', width: 100, sortable: false, menuDisabled: false, filter: {
                                type: 'string'
                            }
                        },
                    ]
                });
                var init_wind = getTop().Ext.create('Ext.window.Window', {
                    title: '未清生产订单',
                    width: 830,
                    height: 480,
                    modal: true,
                    maximizable: true,
                    items: [grid],
                    listeners: {
                        resize: function (wn, width, height, eOpts) {
                            let grid = wn.items.items[0];
                            grid.setHeight(height - 80);
                            grid.setWidth(width - 15);
                            oneTbar.setSize(400, 100);
                        }
                    },
                    fbar: [
                        {
                            type: 'button',
                            text: '选择',
                            handler: function () {
                                let selectrows = grid.getSelectionModel().getSelection();
                                if (selectrows.length > 0) {
                                    for (var i = 0; i < selectrows.length; i++) {
                                        var item = selectrows[i].data;

                                        var temp = AllSettings.filter(function (p) {
                                            if (item.Inventory_ID == p.Inventory_ID) {
                                                return p;
                                            }
                                        });
                                        var bcp_invid = '';
                                        var Style = temp.length > 0 ? temp[0].Style : 1;
                                        var CQty = (item.CQty * Style) / 1000;
                                        var view = theGrid.collectionView;
                                        var newItem = view.addNew();
                                        let nowDate = new Date().format('yyyy/MM/dd');
                                        if (new Date(item.DuDate) < new Date(nowDate)) {
                                            let temp_date = nowDate.format('yyyy/MM/dd');
                                            newItem.Date = getTop().wijmo.Globalize.parseDate(temp_date, 'yyyy/MM/dd');
                                            newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(temp_date, 'yyyy/MM/dd');
                                            newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(temp_date, 'yyyy/MM/dd');
                                        } else {
                                            newItem.Date = getTop().wijmo.Globalize.parseDate(item.DuDate, 'yyyy/MM/dd');
                                            newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.DuDate, 'yyyy/MM/dd');
                                            newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.DuDate, 'yyyy/MM/dd');
                                        }
                                        newItem.ParentID = rows.ParentID;
                                        newItem.FStatus = item.FStatus;
                                        newItem.Capacity = item.Capacity;
                                        newItem.OnePlanMAX = temp.length > 0 ? temp[0].OnePlanMAX : '';
                                        newItem.Resource_ID = rows.Resource_ID;
                                        newItem.Resource_index = rows.Resource_index;
                                        newItem.Resource = rows.Resource;
                                        newItem.Scheduling = '';
                                        newItem.MfgCatID = temp.length > 0 ? temp[0].SandType : '';
                                        newItem.SandTypeId = temp.length > 0 ? temp[0].SandTypeId : '';
                                        newItem.Number = item.NO;
                                        newItem.BcpNumber = item.LvWanActl;
                                        newItem.Inventory_ID = item.Inventory_ID;
                                        newItem.Description = temp.length > 0 ? temp[0].Description : '';
                                        newItem.StdInventory_ID = bcp_invid;
                                        newItem.BatchNO = item.BatchNO;
                                        newItem.PlanQty = CQty;
                                        newItem.Lock = 0;
                                        newItem.PlanNpkg = item.CQty;
                                        newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.ReqDate, 'yyyy/MM/dd');
                                        newItem.PlanDateEnd = getTop().wijmo.Globalize.parseDate(item.DuDate, 'yyyy/MM/dd');
                                        newItem.Matching = item.Matching;
                                        newItem.PlanDate = CQty / (temp.length > 0 ? temp[0].Capacity : 1);
                                        newItem.Unit_Weight = temp.length > 0 ? temp[0].Style : '';
                                        newItem.HCapacity = temp.length > 0 ? temp[0].Capacity : '';
                                        newItem.GcdType = 0;
                                        newItem.SaOrderKey = 0;
                                        view.commitNew();
                                    }
                                    theGrid.collectionView.refresh();
                                    init_wind.close();
                                    return true;
                                } else {
                                    Alert('提示：', '请选择数据！');
                                    return false;
                                }
                            }
                        }, {
                            type: 'button',
                            text: '取消',
                            handler: function () {
                                init_wind.close();
                            }
                        }
                    ]
                });
                init_wind.show();
            }
            let con_ary = [
                //{ c: "NO", cp: 'notin', v: gd_arry.join(";") },
                { c: "Type", cp: '=', v: 1 },
                { c: "Closed", cp: '=', v: 0 },
                { c: "Des_StockID", cp: '=', v: rows.ParentID }
            ];
            cond.child = con_ary;
            Wait.Start(null, "正在执行操作，请稍候.....");
            list = getListWithMultParams("Material_Issue_Plan_Tree_List_Use_Wijmo", { _cdt: jsonEncode(cond) },
                null, {
                callback: function (vitems) {
                    Wait.hide();
                    wnd(vitems, rows == undefined ? '' : rows);
                    let pid = rows.ParentID;
                    let ary1 = [];
                    foreach(WorkShopLine, function (el) {
                        if (el.Parent_ID == pid) {
                            let obj = new Object();
                            obj.id = el.Description;
                            obj.name = el.Description;
                            ary1.push(obj);
                        }
                    });
                    CreateDataMap(ary1, "Resource");
                },
                async: function () {

                }
            });
        }
    });
    /***
     * 齐套分析
     * 排产界面中的工单与sap给的数据做对比，齐套标记绿色，不齐套标记红色
    */
    let btnBundleAnalysis = Ext.create('Ext.Button', {
        tooltip: '齐套分析',
        glyph: 0xf058,
        handler: function () {
            let cv = theGrid.itemsSource;
            let Des_StockID = cv.currentItem.ParentID

            var gd_list = getListWithMultParams("Material_Issue_Plan_SAP", { Des_StockID: Des_StockID, Matching: 0 });
            var source = theGrid.itemsSource.items;
            foreach(source, function (item) {
                if (item.GcdType == 4) {
                    return;
                }
                var temp = gd_list.filter(function (p) {
                    if (p.NO == item.Number) {
                        return p;
                    }
                });
                if (temp.length > 0) {
                    item.Matching = 0;
                } else {
                    item.Matching = 1;
                }
            });
            theGrid.collectionView.refresh();
            Alert('提示：', '齐套分析完成');
        }
    });

    /***
     * 查看指定工单缺料
     * 根据选择的工去sap的接口查询缺少的物料
     **/
    let btnViewGdItemShortage = Ext.create('Ext.Button', {
        tooltip: '查看指定工单缺料',
        glyph: 0xf689,
        handler: function () {
            var Garray = [];
            let cv = theGrid.itemsSource;
            if (cv.currentItem == null || cv.currentItem == '' || cv.currentItem == undefined) {
                Alert('提示：', '请选择需要查询的物料！');
                return false;
            } else {
                Garray.push({
                    AUFNR: cv.currentItem.Number
                });
                var cond = {
                    t: "and", child: [{ c: "BatchNO", cp: '=', v: cv.currentItem.BatchNO }]
                }
                let bcplist = getListWithMultParams("Material_Issue_Plan", { _cdt: jsonEncode(cond) });
                if (bcplist.length > 0) {
                    for (let index = 0; index < bcplist.length; index++) {
                        const element = bcplist[index];
                        Garray.push({ AUFNR: element.NO });
                    }
                }
            }
            var arg = {
                //url: 'http://saperpqas.nipponpaint.com.cn:8000/sap/bc/srt/rfc/sap/zws_eccaps_03/510/zws_eccaps_03/zws_eccaps_03',
                url: 'http://sapr3pci01.nipponpaint.com.cn:8000/sap/bc/srt/rfc/sap/zws_eccaps_03/500/zws_eccaps_03/binding',
                username: 'APSLOGON',
                password: 'initinit',
                method: 'zws_eccaps_03',
                argument: {
                    ET_PRODRET: jsonEncode([]),
                    IT_AUFNR: jsonEncode(Garray),
                    ET_SHORTMAT: jsonEncode([])
                },
            };
            Wait.Start(null, "数据同步中........");
            var ret = callWebService(arg, true, (ret) => {
                Wait.hide();
                if (!ret[0].success) {
                    alert(ret[0].message);
                    return;
                }
                var retobj = jsonDecode(ret[1]);
                var st_data = [];
                foreach(retobj.ET_SHORTMAT, function (ve) {
                    let temp = getItemWithMultParams("Material_Issue_Plan", { NO: ve.AUFNR });
                    var obj = new Object();
                    obj.AUFNR = ve.AUFNR;
                    obj.DATE = temp != null ? new Date(temp.Date).format('yyyy-MM-dd') : null;
                    obj.MATNR = ve.MATNR;
                    obj.MAKTX = ve.MAKTX;
                    obj.BDMNG = ve.BDMNG;
                    obj.QL_QTY = ve.QL_QTY;
                    obj.MEINS = ve.MEINS;
                    st_data.push(obj);
                });
                var grid = Ext.create('Ext.grid.Panel', {
                    store: Ext.create('Ext.data.Store', {
                        fields: ['AUFNR', 'DATE', 'MATNR', 'MAKTX', 'BDMNG', 'QL_QTY', 'MEINS'],
                        data: st_data
                    }),
                    height: 400,
                    stripeRows: true,
                    viewConfig: { forceFit: true },
                    columns: [
                        { header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true },
                        { header: 'SAP生产单号', dataIndex: 'AUFNR', width: 117, align: 'center', sortable: false, menuDisabled: true },
                        { header: '生产单日期', dataIndex: 'DATE', width: 117, align: 'center', sortable: false, menuDisabled: true },
                        { header: '组件物料编码', dataIndex: 'MATNR', width: 100, align: 'center', sortable: false, menuDisabled: true },
                        { header: '组件描述', dataIndex: 'MAKTX', width: 330, align: 'center', sortable: false, menuDisabled: true },
                        { header: '组件数量', dataIndex: 'BDMNG', width: 73, align: 'center', sortable: false, menuDisabled: true },
                        { header: '缺料数量', dataIndex: 'QL_QTY', width: 73, align: 'center', sortable: false, menuDisabled: true },
                        { header: '单位', dataIndex: 'MEINS', width: 47, align: 'center', sortable: false, menuDisabled: true }
                    ]
                });
                var init_wind = Ext.create('Ext.window.Window', {
                    title: cv.currentItem.Number + ':短缺物料',
                    width: 830,
                    height: 480,
                    modal: true,
                    items: [grid],
                    listeners: {
                        resize: function (wn, width, height, eOpts) {
                            let grid = wn.items.items[0];
                            grid.setHeight(height - 80);
                            grid.setWidth(width - 15);
                        }
                    },
                    fbar: [{
                        type: 'button',
                        text: '确定',
                        handler: function () { init_wind.close(); }
                    }]
                });
                init_wind.show();
            });
        }
    });
    /***
     * 工单缺料明细
     * 将界面中的工单号传入sap的接口查询出工单的缺料明细
    */
    let btnViewGdListShortage = Ext.create('Ext.Button', {
        tooltip: '工单缺料明细',
        glyph: 0xf03a,
        handler: function () {
            var Garray = [];
            var source = theGrid.itemsSource.items;
            let bcppc = [];
            foreach(source, function (item) {
                if (item.Matching == 0) {
                    Garray.push({
                        AUFNR: item.Number
                    });
                    bcppc.push(item.BatchNO);
                }
            });
            var cond = {
                t: "and", child: [{ c: "BatchNO", cp: 'in', v: bcppc.join(';') }]
            }
            let bcplist = getListWithMultParams("Material_Issue_Plan", { _cdt: jsonEncode(cond) });
            if (bcplist.length > 0) {
                for (let index = 0; index < bcplist.length; index++) {
                    const element = bcplist[index];
                    Garray.push({ AUFNR: element.NO });
                }
            }
            Wait.Start(null, "数据同步中........");
            var arg = {
                //url: 'http://saperpqas.nipponpaint.com.cn:8000/sap/bc/srt/rfc/sap/zws_eccaps_03/510/zws_eccaps_03/zws_eccaps_03',
                url: 'http://sapr3pci01.nipponpaint.com.cn:8000/sap/bc/srt/rfc/sap/zws_eccaps_03/500/zws_eccaps_03/binding',
                username: 'APSLOGON',
                password: 'initinit',
                method: 'zws_eccaps_03',
                argument: {
                    ET_PRODRET: jsonEncode([]),
                    IT_AUFNR: jsonEncode(Garray),
                    ET_SHORTMAT: jsonEncode([])
                },
            };
            var st_data = [];
            var ret = callWebService(arg, true, (ret) => {
                Wait.hide();
                if (!ret[0].success) {
                    alert(ret[0].message);
                    return;
                }
                var retobj = jsonDecode(ret[1]);

                foreach(retobj.ET_SHORTMAT, function (ve) {
                    let temp = getItemWithMultParams("Material_Issue_Plan", { NO: ve.AUFNR });
                    var obj = new Object();
                    obj.AUFNR = ve.AUFNR;
                    obj.DATE = temp != null ? new Date(temp.Date).format('yyyy-MM-dd') : null;
                    obj.MATNR = ve.MATNR;
                    obj.MAKTX = ve.MAKTX;
                    obj.BDMNG = ve.BDMNG;
                    obj.QL_QTY = ve.QL_QTY;
                    obj.MEINS = ve.MEINS;
                    st_data.push(obj);
                });

                var store = Ext.create('Ext.data.Store', {
                    fields: ['AUFNR', 'DATE', 'MATNR', 'MAKTX', 'BDMNG', 'QL_QTY', 'MEINS'],
                    data: st_data,
                    groupField: 'MATNR',
                });
                console.log(store);
                var grid = Ext.create('Ext.grid.Panel', {
                    store: store,
                    height: 400,
                    stripeRows: true,
                    viewConfig: {
                        forceFit: true
                    },
                    features: [{
                        ftype: 'groupingsummary'
                    }],
                    plugins: {
                        gridfilters: true
                    },
                    columns: [
                        { header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true },
                        { header: 'SAP生产单号', dataIndex: 'AUFNR', width: 117, align: 'center', sortable: false, menuDisabled: true },
                        {
                            header: '生产单日期', dataIndex: 'DATE', width: 117, align: 'center', sortable: false, menuDisabled: false,
                            xtype: 'datecolumn', format: 'Y-m-d',
                            filter: {
                                type: 'date',
                                pickerDefaults: {
                                    // any DatePicker configs
                                }
                            }
                        },
                        { header: '组件物料编码', dataIndex: 'MATNR', width: 100, align: 'center', sortable: false, menuDisabled: true },
                        { header: '组件描述', dataIndex: 'MAKTX', width: 330, align: 'center', sortable: false, menuDisabled: true },
                        { header: '组件数量', dataIndex: 'BDMNG', summaryType: 'sum', width: 73, align: 'center', sortable: false, menuDisabled: true },
                        { header: '缺料数量', dataIndex: 'QL_QTY', summaryType: 'sum', width: 73, align: 'center', sortable: false, menuDisabled: true },
                        { header: '单位', dataIndex: 'MEINS', width: 47, align: 'center', sortable: false, menuDisabled: true }
                    ],
                    tbar: [
                        {
                            text: '导出Excel',
                            glyph: 0xf1c3,
                            handler: function () {
                                grid2Excel(grid, "工单缺料明细");
                            }
                        }
                    ]
                });
                var init_wind = Ext.create('Ext.window.Window', {
                    title: '短缺物料',
                    width: 830,   //Number型，也可以是字符串类型 
                    height: 480,
                    modal: true,
                    maximizable: true,
                    items: [grid],
                    listeners: {
                        resize: function (wn, width, height, eOpts) {
                            let grid = wn.items.items[0];
                            grid.setHeight(height - 80);
                            grid.setWidth(width - 15);
                        },
                        show: function () {
                            Wait.hide();
                        }
                    },
                    fbar: [
                        {
                            type: 'button',
                            text: '确定',
                            handler: function () {
                                init_wind.close();
                            }
                        }
                    ]
                });
                init_wind.show();
            });
        }
    });
    /***
     * 上移
     * 将选择的行记录向上移动一行
     * */
    let btnMoveUpward = Ext.create('Ext.Button', {
        tooltip: '上移',
        glyph: 0xf062,
        listeners: {
            click: {
                buffer: 000,
                fn: function (upbtn, e) {
                    let source = theGrid.itemsSource.items;
                    if (theGrid.selectedItems.length < 1) {
                        Alert('提示：', '请选择操作项');
                        return false;
                    } else {
                        upbtn.disable();
                        let cv = theGrid.collectionView;
                        let rows = theGrid.selectedItems[0];
                        let item_index = rows.index;
                        let new_item_index = item_index - 1

                        if (item_index > 0) {
                            if (new_item_index >= 0) {
                                theGrid.beginUpdate();
                                let item = source[item_index];
                                let newitem = source[new_item_index];
                                let gcd_type = item.GcdType;

                                let old_id = item.index;
                                let new_id = newitem.index;

                                let old_date = item.Date;
                                let new_date = newitem.Date;

                                let old_scheduling = item.Scheduling;
                                let new_scheduling = newitem.Scheduling;

                                let old_scheduleenddate = item.ScheduleEndDate;
                                let new_scheduleenddate = newitem.ScheduleEndDate;

                                if (gcd_type == 4 || item.Lock == 1) {
                                    if (new Date(old_date) - new Date(new_date) == 0 && old_scheduling == new_scheduling) {

                                        item.index = new_id;
                                        newitem.index = old_id;

                                        item.Date = new_date;
                                        newitem.Date = old_date;

                                        item.Scheduling = new_scheduling;
                                        newitem.Scheduling = old_scheduling;

                                        item.ScheduleEndDate = new_scheduleenddate;
                                        newitem.ScheduleEndDate = old_scheduleenddate;
                                    } else {
                                        alert('不能移除固定范围！');
                                    }
                                } else {

                                    item.index = new_id;
                                    newitem.index = old_id;

                                    item.Date = new_date;
                                    newitem.Date = old_date;

                                    item.Scheduling = new_scheduling;
                                    newitem.Scheduling = old_scheduling;

                                    item.ScheduleEndDate = new_scheduleenddate;
                                    newitem.ScheduleEndDate = old_scheduleenddate;
                                }
                                cv.refresh();
                                theGrid.endUpdate();
                            }
                        }
                    }
                }
            }
        }
    });
    /***
     * 下移
     * 将选中的行记录向下移动一行
     * */
    let btnMoveDown = Ext.create('Ext.Button', {
        tooltip: '下移',
        glyph: 0xf063,
        listeners: {
            click: {
                buffer: 000,
                fn: function (downbtn) {
                    let source = theGrid.itemsSource.items;

                    if (theGrid.selectedItems.length < 1) {
                        Alert('提示：', '请选择操作项');
                        return false;
                    } else {
                        downbtn.disable();
                        let cv = theGrid.collectionView;
                        let rows = theGrid.selectedItems[0];
                        let item_index = rows.index;
                        let new_item_index = item_index + 1
                        if (item_index < source.length) {
                            if (new_item_index < source.length) {
                                theGrid.beginUpdate();
                                let item = source[item_index];
                                let newitem = source[new_item_index];
                                let gcd_type = item.GcdType;

                                let old_id = item.index;
                                let new_id = newitem.index;

                                let old_date = item.Date;
                                let new_date = newitem.Date;

                                let old_scheduling = item.Scheduling;
                                let new_scheduling = newitem.Scheduling;

                                let old_scheduleenddate = item.ScheduleEndDate;
                                let new_scheduleenddate = newitem.ScheduleEndDate;

                                if (gcd_type == 4 || item.Lock == 1) {
                                    if (new Date(old_date) - new Date(new_date) == 0 && old_scheduling == new_scheduling) {

                                        item.index = new_id;
                                        newitem.index = old_id;

                                        item.Date = new_date;
                                        newitem.Date = old_date;

                                        item.Scheduling = new_scheduling;
                                        newitem.Scheduling = old_scheduling;

                                        item.ScheduleEndDate = new_scheduleenddate;
                                        newitem.ScheduleEndDate = old_scheduleenddate;
                                    } else {
                                        alert('不能移除固定范围！');
                                    }
                                } else {

                                    item.index = new_id;
                                    newitem.index = old_id;

                                    item.Date = new_date;
                                    newitem.Date = old_date;

                                    item.Scheduling = new_scheduling;
                                    newitem.Scheduling = old_scheduling;

                                    item.ScheduleEndDate = new_scheduleenddate;
                                    newitem.ScheduleEndDate = old_scheduleenddate;
                                }
                                cv.refresh();
                                theGrid.endUpdate();
                            }
                        }
                    }
                }
            }
        }
    });
    /***
     * 自动排序
     * 根据产线日产能、白班、夜班的产能，将每个一个产线下所有工单进行产能分摊
     * */
    let btnAutomaticSorting = Ext.create('Ext.Button', {
        tooltip: '自动排序',
        glyph: 0xf25b,
        handler: function () {
            var res_ary = {};
            var source = theGrid.itemsSource.items;
            var store2 = Ext.create('Ext.data.Store', {
                fields: ['value', 'text'],
                data: []
            });
            //删除洗机工单
            DelEquWash_GD();
            foreach(source, function (item) {
                if (res_ary[item.Resource_ID] == null) {
                    res_ary[item.Resource_ID] = 1;
                    store2.addSorted({
                        value: item.Resource_ID,
                        text: item.Resource
                    });
                }
            });
            var init_wind = Ext.create('Ext.window.Window', {
                title: '选择需要排序的工厂',
                width: 300,   //Number型，也可以是字符串类型 width:'90%'
                height: 200,
                modal: true,
                items: [
                    {
                        xtype: 'panel',
                        layout: 'form',
                        items: [
                            {
                                fieldLabel: '产线',
                                id: 'zd_WIP_ID',
                                xtype: 'combobox',
                                editable: false,
                                queryMode: 'local',
                                valueField: 'value',
                                displayField: 'text',
                                store: store2
                            }
                        ]
                    }
                ],
                fbar: [
                    {
                        type: 'button',
                        text: '确定',
                        handler: function () {
                            var WIP_ID = getTop().Ext.getCmp("zd_WIP_ID").getRawValue();
                            AssessmentOfCapacity(source.sort(function (a, b) { return a.index - b.index }), WIP_ID);
                            init_wind.close();
                            theGrid.collectionView.refresh();
                            theGrid.collapseGroupsToLevel(2);
                        }
                    },
                    {
                        type: 'button',
                        text: '取消',
                        handler: function () {
                            init_wind.close();
                        }
                    }
                ]
            });
            init_wind.show();
        }
    });
    /***
     * 保存
     * 将当前界面的工单数据保存到排产计划表中
     * */
    let btnSave = Ext.create('Ext.Button', {
        tooltip: '保存',
        glyph: 0xf0c7,
        handler: function () {
            var source = theGrid.itemsSource.items;
            //计划主表：ProductionPlanGcd
            // 设置要打开窗口的地址，打开的表用编码表示，此处打开订单表（以创建模式打开）
            var url = "/ProductionPlanGcd/edit?createmode=true";

            // 将查询字符串固定的参数添加到url中，每次打开的窗口都有一些固定的参数存在，如制定数据库编号
            var urlarg = new Array();

            foreach(__fq, function (v, i, leave, name) { urlarg.push(name + "=" + encodeURIComponent(v)); });

            url += "&" + urlarg.join("&");

            // 打开编辑对话框，函数定义见main.js
            parent.openWindow("工单粗排计划", url, 900, 600,
                function () { }, 0xf067,
                // openWindow 的参数initwnd，当窗口打开后执行，设置窗口界面加载完成所执行的函数
                function (newwnd) {
                    var childFrame = newwnd.getChildFrame('ProductionPlanGcdDetail');
                    Wait.Start(null, "正在执行操作，请稍候.....");
                    setTimeout(() => {
                        source.sort(function (a, b) { a.index - b.index });
                        foreach(source, function (v, i) {
                            if (v.GcdType >= 0) {
                                var def = Math.round((new Date(v.PlanDateEnd) - new Date(v.ScheduleEndDate)) / 1000 / 60 / 60 / 24);
                                var obj = new Object();
                                obj.WIP_ID = v.ParentID;
                                obj.Noid = i;
                                obj.CreateDate = v.Date;
                                obj.Resource_index = v.Resource_index;
                                obj.Scheduling = v.Scheduling;
                                obj.IssuleNo = v.Number;
                                obj.ScheduleStartDate = v.ScheduleStartDate;
                                obj.ScheduleEndDate = v.ScheduleEndDate;
                                obj.ScheduleDateDifference = def;
                                obj.CustomerKey = v.SaOrderKey;//.substring(s.lastIndexOf("/") + 1);
                                obj.BatchNO = v.BatchNO;
                                obj.PlanNpkg = v.PlanNpkg;
                                obj.StdInventory_ID = v.StdInventory_ID;
                                obj.MfgCatID = v.MfgCatID;
                                obj.Unit_Weight = v.Unit_Weight;
                                obj.HCapacity = v.HCapacity;
                                obj.Summary = v.Summary;
                                obj.Matching = v.Matching;
                                obj.Resource_ID = v.Resource_ID;
                                obj.Inventory_id = v.Inventory_ID;
                                obj.PbeginDate = v.PlanDateStart;
                                obj.PEndDate = v.PlanDateEnd;
                                obj.MfgPlanTime = v.PlanDate;
                                obj.IssueQty = v.PlanQty;
                                obj.ProQty = v.PlanQty;
                                obj.Lock = v.Lock;
                                childFrame.addChildRow(obj);
                            }
                        });
                        newwnd.setPropertyValue(null, 'Type', 2);
                        newwnd.setPropertyValue(null, 'WIP_ID', source[0].ParentID);
                        Wait.hide();
                    }, 1000);
                }, null, isjsschema);
        }
    });
    /***
     * 编辑虚拟工单
     * 修改选择中的虚拟工单
     * */
    let btnVirtualTicketEdit = new Ext.Button({
        tooltip: '编辑虚拟工单',
        text: '虚',
        hidden: false,
        glyph: 0xf14b,
        handler: function () {
            let cv = theGrid.itemsSource;
            let row = cv.currentItem;
            if (row.GcdType == 4) {
                let Gcd_No = row.Number.match(/(\S*)-/)[1];
                let source = theGrid.itemsSource.items;
                let gd_status = getListWithMultParams("TblVirtualTicket", { EvidenceNumber: '=' + Gcd_No });
                if (Gcd_No == null || Gcd_No == "" || Gcd_No == undefined) {
                    Alert('提示：', '请选择需要修改的虚拟工单！');
                    return false;
                } else if (gd_status[0].Verify == 1) {
                    Alert('提示：', '该工单已审核，无法编辑！');
                    return false;
                } else {
                    getTopWindow().openWindow("虚拟工单", "/TblVirtualTicket/edit?editmode=true&EvidenceNumber=" + Gcd_No, 900, 600, function (v) {
                        if (v != null && v[0].success == true) {
                            let child_list = getListWithMultParams("TblVirtualTicketDetails", { EvidenceNumber: v[1].EvidenceNumber });
                            foreach(child_list, function (el, i) {
                                i = i + 1;
                                var temp = WorkShopLine.filter(function (p) {
                                    if (v[1].ProductionLine == p.Code_ID) {
                                        return p;
                                    }
                                });
                                var desc = LocaltblItem.filter(function (p) {
                                    return p.FCode === el.Shift;
                                });
                                var desc = source.filter(function (p) {
                                    if (p.Number === el.EvidenceNumber + '-' + el.NOID) {
                                        p.Resource_ID = temp.length > 0 ? temp[0].Description : '';
                                        p.Resource = temp.length > 0 ? temp[0].Description : '';
                                        p.Resource_index = 1;
                                        p.ParentID = v[1].Factory;
                                        p.Date = getTop().wijmo.Globalize.parseDate(el.Date, 'yyyy/MM/dd');
                                        p.PlanDateStart = getTop().wijmo.Globalize.parseDate(el.Date, 'yyyy/MM/dd');
                                        //p.Scheduling = desc.length > 0 ? desc[0].FDescript : '';
                                        switch (el.Shift) {
                                            case "白班":
                                                p.Scheduling = '001';
                                                break;
                                            case "夜班":
                                                p.Scheduling = '002';
                                                break;
                                            case "早班":
                                                p.Scheduling = '003';
                                                break;
                                            case "晚班":
                                                p.Scheduling = '004';
                                                break;
                                            default: p.Scheduling = el.Shift;
                                        }
                                        p.Inventory_ID = '虚拟工单';
                                        p.Number = el.EvidenceNumber + '-' + el.NOID;
                                        p.PlanQty = el.VirtualCapacity;
                                        p.PlanDate = el.VirtualWork;
                                        p.Lock = 1;
                                        p.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(el.Date, 'yyyy/MM/dd');
                                        p.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(el.Date, 'yyyy/MM/dd');
                                        p.Summary != null && el.Reason != "" ? el.Reason + ':' + v[1].Summary : v[1].Summary;
                                        p.GcdType = 4;
                                    }
                                });
                            });
                            theGrid.collectionView.refresh();
                        }
                    });
                }
            } else {
                Alert('提示：', '请选择虚拟工单！');
                return false;
            }

        }
    });
    /***
     * 读取虚拟工单
     * 选择需要插入的虚拟工单数据插入到当前排产界面
     * */
    let btnVirtualTicketRead = new Ext.Button({
        tooltip: '读取虚拟工单',
        text: '虚',
        hidden: false,
        glyph: 0xf518,
        handler: function () {
            let source = theGrid.itemsSource.sourceCollection;
            let gd_arry = [];
            let list;
            var cond = {
                t: "and", child: []
            }
            foreach(source, function (item, i) {
                if (item.GcdType == 4) {
                    gd_arry.push(item.Number.match(/(\S*)-/)[1]);
                }
            });

            gd_arry = gd_arry.distinct();
            let gcd = gd_arry.join(';');
            let con_ary = [
                { c: "EvidenceNumber", cp: 'notin', v: gcd },
                { c: "Verify", cp: '=', v: 1 }
            ];
            cond.child = con_ary;
            function wnd(list) {
                foreach(list, function (el) {
                    var work = WorkShopLine.filter(function (p) {
                        if (p.Code_ID == el.Factory) {
                            return p;
                        }
                    });
                    var line = WorkShopLine.filter(function (p) {
                        if (p.Code_ID == el.ProductionLine) {
                            return p;
                        }
                    });
                    el.Factory_name = work.length == 0 ? "" : work[0].Description;
                    el.ProductionLine_name = line.length == 0 ? "" : line[0].Description;
                });
                var store = Ext.create('Ext.data.Store', {
                    fields: ['EvidenceNumber', 'Factory', 'Factory_name', 'ProductionLine', 'ProductionLine_name', 'BeginDate', 'EndDate', 'Maker', 'SumWrkHour', 'SumCapacity', 'Reason', 'Summary'],
                    data: list
                });
                var grid = getTop().Ext.create('Ext.grid.Panel', {
                    store: store,
                    region: 'south',
                    frame: false,
                    width: 900,
                    height: '100%',
                    viewConfig: {
                        columnLines: true,
                        stripeRows: true,
                        enableTextSelection: true,
                        animateShadow: true,
                        forceFit: true
                    },
                    selModel: {
                        mode: 'Single',
                        checkboxSelect: true,
                        injectCheckbox: 1,
                        type: 'checkboxmodel'
                    },
                    columns: [
                        { header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true },
                        {
                            dataIndex: 'EvidenceNumber', header: '工单号', width: 120, sortable: false, menuDisabled: true
                        },
                        { dataIndex: 'Factory', header: '工厂', hidden: true, width: 109, sortable: false, menuDisabled: true },
                        { dataIndex: 'Factory_name', header: '工厂', width: 109, sortable: false, menuDisabled: true },
                        {
                            dataIndex: 'ProductionLine', header: '产线', hidden: true, width: 87, sortable: false, menuDisabled: true
                        },
                        { dataIndex: 'ProductionLine_name', header: '产线', width: 109, sortable: false, menuDisabled: true },
                        { dataIndex: 'BeginDate', header: '开始日期', width: 112, sortable: false, menuDisabled: true },
                        { dataIndex: 'EndDate', header: '截止日期', width: 112, sortable: false, menuDisabled: true },
                        { dataIndex: 'SumWrkHour', header: '总虚拟工时', width: 74, sortable: false, menuDisabled: true },
                        { dataIndex: 'SumCapacity', header: '总虚拟产能', width: 61, sortable: false, menuDisabled: true },
                        { dataIndex: 'Reason', header: '原因', width: 100, sortable: false, menuDisabled: true },
                        { dataIndex: 'Summary', header: '备注', width: 74, sortable: false, menuDisabled: true },
                        { dataIndex: 'Maker', header: '制单人', width: 200, sortable: false, menuDisabled: true },
                    ]
                });
                var init_wind = getTop().Ext.create('Ext.window.Window', {
                    title: '虚拟工程单',
                    width: 830,
                    height: 480,
                    modal: true,
                    maximizable: true,
                    items: [grid],
                    listeners: {
                        resize: function (wn, width, height, eOpts) {
                            let grid = wn.items.items[0];
                            grid.setHeight(height - 80);
                            grid.setWidth(width - 15);
                        }
                    },
                    fbar: [
                        {
                            type: 'button',
                            text: '选择',
                            handler: function () {
                                let selectrows = grid.getSelectionModel().getSelection();
                                if (selectrows.length > 0) {
                                    let selectrow = selectrows[0].data;
                                    let child_list = getListWithMultParams("TblVirtualTicketDetails", { EvidenceNumber: selectrow.EvidenceNumber });
                                    foreach(child_list, function (item, i) {
                                        i = i + 1;
                                        let view = theGrid.collectionView;
                                        let newItem = view.addNew();
                                        var temp = WorkShopLine.filter(function (p) {
                                            if (selectrow.ProductionLine == p.Code_ID) {
                                                return p;
                                            }
                                        });
                                        var desc = LocaltblItem.filter(function (p) {
                                            return p.FCode === item.Shift;
                                        });
                                        newItem.Resource_ID = temp.length > 0 ? temp[0].Description : '';
                                        newItem.Resource = temp.length > 0 ? temp[0].Description : '';
                                        newItem.Resource_index = 1;
                                        newItem.ParentID = selectrow.Factory;
                                        newItem.Date = getTop().wijmo.Globalize.parseDate(item.Date, 'yyyy/MM/dd');
                                        newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(item.Date, 'yyyy/MM/dd');
                                        //newItem.Scheduling = desc.length > 0 ? desc[0].FDescript : '';
                                        switch (item.Shift) {
                                            case "白班":
                                                newItem.Scheduling = '001';
                                                break;
                                            case "夜班":
                                                newItem.Scheduling = '002';
                                                break;
                                            case "早班":
                                                newItem.Scheduling = '003';
                                                break;
                                            case "晚班":
                                                newItem.Scheduling = '004';
                                                break;
                                            default: newItem.Scheduling = item.Shift;
                                        }
                                        newItem.Inventory_ID = '虚拟工单';
                                        newItem.Lock = 1;
                                        newItem.Number = item.EvidenceNumber + '-' + item.NOID;
                                        newItem.PlanQty = item.VirtualCapacity;
                                        newItem.PlanDate = item.VirtualWork;
                                        newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(item.Date, 'yyyy/MM/dd');
                                        newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(item.Date, 'yyyy/MM/dd');
                                        newItem.GcdType = 4;
                                        newItem.Summary = item.Reason != null && item.Reason != "" ? item.Reason + ':' + selectrow.Summary : selectrow.Summary;
                                        view.commitNew();
                                    });
                                    theGrid.collectionView.refresh();
                                    init_wind.close();
                                    return true;
                                } else {
                                    Alert('提示：', '请选择数据！');
                                    return false;
                                }
                            }
                        }, {
                            type: 'button',
                            text: '取消',
                            handler: function () {
                                init_wind.close();
                            }
                        }
                    ]
                });
                init_wind.show();
            }
            Wait.Start(null, "正在执行操作，请稍候.....");
            list = getListWithMultParams("TblVirtualTicket", { _cdt: jsonEncode(cond) },
                null, {
                callback: function (vitems) {
                    Wait.hide();
                    wnd(vitems);
                },
                async: function () {

                }
            });
        }
    });

    /***
     * 查看全览表
     * 打开全览表数据
     * */
    let btnViewOverview = Ext.create('Ext.Button', {
        tooltip: '查看全览表',
        glyph: 0xf15c,
        handler: function () {
            let cv = theGrid.itemsSource;
            let invid;
            if (cv.currentItem == null || cv.currentItem == '' || cv.currentItem == undefined) {
                Alert('提示：', '请选择需要查询的物料！');
                return false;
            } else {
                invid = cv.currentItem.Inventory_ID
                getTopWindow().openWindow("全览表", "/Inventory?disble_operate_type=Add,Edit,Delete,Print,Record,BackRecord,Verify&Inventory_ID=" + invid
                    , 1100, 600, function () { });
            }
        }
    });

    /***
     * 导出Excel
     * 将当前界面的排产数据导出到Excel文件中
     * */
    let btnExportExcel = Ext.create('Ext.Button', {
        tooltip: '导出Excel',
        glyph: 0xf1c3,
        handler: function () {
            Wait.Start(null, "正在执行操作，请稍候.....");
            setTimeout(() => {
                theGrid.collapseGroupsToLevel(3);
                getTop().wijmo.grid.xlsx.FlexGridXlsxConverter.saveAsync(theGrid, { includeColumnHeaders: true }, '工单粗排.xlsx');
                theGrid.collapseGroupsToLevel(2);
                Wait.hide();
            }, 500);
        }
    });
    /***
     * 删除
     * 将选择的行记录数据从当前排产界面中移除
     * */
    let btnDelete = Ext.create('Ext.Button', {
        tooltip: '删除',
        glyph: 0xf2ed,
        handler: function () {
            Confirm('提示：', '确定删除？', function () {
                var cv = theGrid.itemsSource;
                cv.remove(cv.currentItem);
                cv.refresh();
            }, null, null);
        }
    });
    /***
     * 初始化数据
     * 按工厂、产线、日期进行数据初始化
     * */
    let btnInitializationData = Ext.create('Ext.Button', {
        tooltip: '初始化数据',
        glyph: 0xf00a,
        handler: function () {
            var source = theGrid.itemsSource.sourceCollection;
            var view = theGrid.collectionView;
            var CxCbox = new Ext.form.field.Tag({
                xtype: 'tagfield',
                fieldLabel: '产线',
                store: new Ext.create('Ext.data.Store', {
                    fields: ['value', 'text'],
                    data: []
                }),
                displayField: 'text',
                valueField: 'value',
                queryMode: 'local',
                filterPickList: true,
                labelWidth: 50
            });
            var init_wind = Ext.create('Ext.window.Window', {
                title: '初始化数据',
                width: 400,   //Number型，也可以是字符串类型 width:'90%'
                height: 300,
                modal: true,
                items: [
                    {
                        xtype: 'panel',
                        layout: 'form',
                        items: [
                            {
                                fieldLabel: '车间',
                                id: 'WIP_ID',
                                xtype: 'combobox',
                                editable: false,
                                queryMode: 'local',
                                valueField: 'value__',
                                displayField: 'TheNameValue',
                                store: getTop().newJsonStore({
                                    fields: ['value__', 'TheNameValue'],
                                    data: [
                                        { "value__": "", "TheNameValue": "[无]" },
                                        { "value__": "WIP_ID", "TheNameValue": "[浏览]" },
                                    ]
                                }),
                                listeners: {
                                    afterRender: function (combo) {
                                        combo.setValue(combo.getStore().getAt(0).get("value__"));//同时下拉框会将与name为firstValue值对应的 text显示
                                    },
                                    select: function (combo) {
                                        var c1 = combo.getValue();
                                        var val;
                                        var url = "/WorkShopLine?disble_operate_type=Add,Edit,Delete,Search&selectmode=true&ps=500&Type=1,2";
                                        if (c1 == "WIP_ID") {
                                            combo.setValue(combo.getStore().getAt(0).get("value__"));
                                            getTop().openWindow("车间档案", url, 800, 600, function (v) {
                                                if (v != null && typeof (v) == "object") {
                                                    if (v.length > 1) {
                                                        if (v[0].success == 'true' || v[0].success == true) {
                                                            foreach(v, function (vitem) {
                                                                val = vitem.Code_ID;
                                                            });
                                                            var flg = 0;
                                                            for (var i = 0; i < combo.getStore().getCount(); i++) {
                                                                var recored = combo.getStore().getAt(i).get("value__");
                                                                if (recored == val) {
                                                                    flg++;
                                                                }
                                                            }
                                                            if (flg == 0) {
                                                                combo.getStore().add({ value__: val, TheNameValue: val });
                                                            }
                                                            combo.setValue(val);
                                                            let shopline_ary = WorkShopLine.filter(function (p) {
                                                                if (p.Parent_ID == val) {
                                                                    return p;
                                                                }
                                                            });
                                                            var cxCbox_data = [];
                                                            foreach(shopline_ary, function (item) {
                                                                cxCbox_data.push({
                                                                    value: item.Code_ID,
                                                                    text: item.Description
                                                                });
                                                            });
                                                            CxCbox.getStore().loadData(cxCbox_data);
                                                            CxCbox.resumeEvents();
                                                        }
                                                    }
                                                }
                                            }, "", null, null, isjsschema);
                                        }
                                    }
                                }
                            }, CxCbox,
                            {
                                fieldLabel: '排产天数',
                                id: 'pc_days',
                                name: 'pc_days',
                                value: 1,
                                xtype: 'numberfield',
                                AllowNegative: false,
                                minValue: 0,
                                maxValue: 100,
                                listeners: {
                                    change: function (field, value) {
                                        if (value == 0 || value < 0) {
                                            field.setValue(1);
                                        }
                                    }
                                }
                            }
                        ]
                    }
                ],
                fbar: [
                    {
                        type: 'button',
                        text: '确定',
                        handler: function () {
                            var pc_days = getTop().Ext.getCmp("pc_days").getRawValue();
                            //var Resource_ID = getTop().Ext.getCmp("Resource_ID").getRawValue();
                            //let cxval_ary = CxCbox.getRawValue();
                            let cxtext_ary = CxCbox.getValue();
                            let cx_ary = [];
                            foreach(CxCbox.getValueRecords(), function (row) {
                                cx_ary.push({
                                    value: row.get('value'),
                                    text:  row.get('text')
                                });
                            });
                            if (cxtext_ary.length == 0) {
                                Alert('提示：', '请选择产线');
                                return false;
                            }
                            if (pc_days == 0 || pc_days < 0) {
                                Alert('提示：', '请填写正确的排产天数');
                                return false;
                            }
                            var WIP_ID = getTop().Ext.getCmp("WIP_ID").getRawValue();
                            Confirm('提示：', '确定初始化？', function () {
                                source.splice(0, source.length);
                                theGrid.collectionView.refresh();
                                foreach(cx_ary, function (item, j) {
                                    var temp_date = new Date().format('yyyy/MM/dd');
                                    ResourceIndex.push({
                                        Resource_ID: item.value,
                                        Index: j
                                    });
                                    for (var i = 0; i < pc_days; i++) {
                                        var newItem = view.addNew();
                                        newItem.ParentID = WIP_ID;
                                        newItem.GcdType = -1;
                                        newItem.Date = getTop().wijmo.Globalize.parseDate(new Date(temp_date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                        newItem.Resource_index = j;
                                        newItem.Resource_ID = item.value;
                                        newItem.Resource = item.text;
                                        newItem.Number = '';
                                        newItem.Scheduling = '001';
                                        newItem.Inventory_ID = '';
                                        newItem.Description = '';
                                        newItem.BatchNO = '';
                                        newItem.PlanQty = 0;
                                        newItem.PlanDateStart = getTop().wijmo.Globalize.parseDate(new Date(temp_date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                        newItem.PlanDate = 0;
                                        newItem.MfgCatID = '';
                                        newItem.SandTypeId = '';
                                        newItem.SaOrderKey = 0;
                                        newItem.FStatus = '';
                                        newItem.Lock = 0;
                                        newItem.Capacity = 0;
                                        newItem.OnePlanMAX = '';
                                        newItem.StdInventory_ID = '';
                                        newItem.PlanDateEnd = '';
                                        newItem.Matching = '';
                                        newItem.Style = '';
                                        newItem.Capacity = 0;
                                        newItem.ScheduleStartDate = getTop().wijmo.Globalize.parseDate(new Date(temp_date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                        newItem.ScheduleEndDate = getTop().wijmo.Globalize.parseDate(new Date(temp_date).format('yyyy/MM/dd'), 'yyyy/MM/dd');
                                        view.commitNew();
                                        temp_date = addDate(temp_date, 1);
                                    }
                                });
                                let pid = WIP_ID;
                                let ary1 = [];
                                foreach(WorkShopLine, function (el) {
                                    if (el.Parent_ID == pid) {
                                        let obj = new Object();
                                        obj.id = el.Description;
                                        obj.name = el.Description;
                                        ary1.push(obj);
                                    }
                                });
                                init_wind.close();
                                theGrid.collectionView.refresh();
                                theGrid.collapseGroupsToLevel(2);
                                CreateDataMap(ary1, "Resource");
                            }, function () { }, null);
                        }
                    },
                    {
                        type: 'button',
                        text: '取消',
                        handler: function () {
                            init_wind.close();
                        }
                    }
                ]
            });
            init_wind.show();
        }
    });
    /***
     * 刷新工厂日历、班制、班次、全览表、洗机工单、车间档案、生产工单数据
     * */
    let btnRefreshData = Ext.create('Ext.Button', {
        tooltip: '刷新工厂日历、班制、班次、全览表、洗机工单、车间档案、生产工单数据',
        glyph: 0xf021,
        handler: function () {
            Wait.Start(null, "数据同步中.....");
            setTimeout(() => {
                sourceData();
                Wait.hide();
            }, 1000);
            Alert('提示：', '档案数据刷新完成');
        }
    });
    /**
     * 锁定工单
     * 按产线、日期、班次进行批量锁定工单
     **/
    let btnLockTicket = Ext.create('Ext.Button', {
        tooltip: '按产线、日期、班次进行批量锁定工单',
        glyph: 0xf023,
        handler: function () {
            let source = theGrid.itemsSource.items;
            let resourceStore = Ext.create('Ext.data.Store', {
                fields: ['value', 'text'],
                data: []
            });
            let schedulingStore = Ext.create('Ext.data.Store', {
                fields: ['value', 'text'],
                data: []
            });
            let resourceCombox = Ext.create('Ext.form.ComboBox', {
                store: resourceStore,
                queryMode: 'local',
                displayField: 'text',
                valueField: 'value',
                editable: false
            });
            let dateField = {
                xtype: 'datefield',
                anchor: '100%',
                name: 'date',
                format: "Y/m/d",
                value: new Date()
            }
            let schedulingCombox = Ext.create('Ext.form.ComboBox', {
                store: schedulingStore,
                queryMode: 'local',
                displayField: 'text',
                editable: false,
                valueField: 'value'
            });
            let res_ary;
            res_ary = JsonArrayGroup(source);
            foreach(res_ary, function (item) {
                resourceStore.addSorted({
                    value: item.Resource_ID,
                    text: item.Resource
                });
            });
            foreach(LocaltblItem, function (el) {
                schedulingStore.addSorted({
                    value: el.FCode,
                    text: el.FDescript
                });
            });
            let lockGrid = getTop().Ext.create('Ext.grid.Panel', {
                store: lockStore,
                region: 'south',
                frame: false,
                width: 900,
                height: '100%',
                viewConfig: {
                    columnLines: true,
                    stripeRows: true,
                    enableTextSelection: true,
                    animateShadow: true,
                    forceFit: true
                },
                selModel: {
                    mode: 'MULTI',
                    checkboxSelect: true,
                    injectCheckbox: 1,
                    type: 'checkboxmodel'
                },
                plugins: {
                    ptype: 'cellediting',
                    clicksToEdit: 1
                },
                columns: [
                    {
                        header: '', xtype: 'rownumberer', width: 45, align: 'center', sortable: false, menuDisabled: true
                    },
                    {
                        dataIndex: 'Resource_ID', header: '产线', width: 170, sortable: false, menuDisabled: true, editor: {
                            completeOnEnter: false, field: resourceCombox
                        }
                    },
                    {
                        dataIndex: 'Date', header: '日期', width: 120, sortable: false, menuDisabled: true,
                        completeOnEnter: false, field: dateField, renderer: function (value) {
                            return value.format('yyyy/MM/dd');
                        }
                    },
                    {
                        dataIndex: 'Scheduling', header: '班次', width: 120, sortable: false, menuDisabled: true,
                        completeOnEnter: false, field: schedulingCombox,
                        renderer: function (value) {
                            let desc = LocaltblItem.filter(function (p) {
                                return p.FCode === value;
                            });
                            return desc.length == 0 ? '' : desc[0].FDescript;
                        }
                    }, {
                        dataIndex: 'Lock', header: '锁定', width: 70, sortable: false, menuDisabled: true,
                        completeOnEnter: false,
                        field: Ext.create('Ext.form.ComboBox', {
                            store: Ext.create('Ext.data.Store', {
                                fields: ['value', 'text'],
                                data: [{ value: 1, text: '已锁' }, { value: 0, text: '未锁' }]
                            }),
                            queryMode: 'local',
                            displayField: 'text',
                            editable: false,
                            valueField: 'value',
                            value: 0
                        }),
                        renderer: function (value) {
                            return value == 1 ? '已锁' : '未锁';
                        }
                    }
                ],
                tbar: [
                    {
                        text: '新增',
                        glyph: 0xf067,
                        handler: function () {
                            lockStore.add({
                                Resource_ID: '',
                                Date: new Date(),
                                Scheduling: '',
                                Lock: 1,
                            });
                        }
                    },
                    {
                        text: '删除',
                        glyph: 0xf2ed,
                        handler: function () {
                            let rows = lockGrid.getSelection();
                            if (rows.length > 0) {
                                foreach(rows, function (rec) {
                                    lockStore.remove(rec);
                                })
                            } else {
                                Alert('提示：', '请选择需要操作的数据');
                                return false;
                            }
                        }
                    }
                ]
            });
            var init_wind = Ext.create('Ext.window.Window', {
                title: '锁定工单',
                width: 600,
                height: '90%',
                modal: true,
                items: [lockGrid],
                fbar: [
                    {
                        type: 'button',
                        text: '锁定',
                        glyph: 0xf0c7,
                        handler: function () {
                            let flg = LockGcd(source)
                            if (flg) {
                                Alert('提示：', '已完成！');
                                init_wind.close();
                            }
                        }
                    },
                    {
                        type: 'button',
                        text: '取消',
                        glyph: 0xf410,
                        handler: function () {
                            init_wind.close();
                        }
                    }
                ]
            });
            init_wind.show();
        }
    });
    //展开
    let btnExpansion = Ext.create('Ext.Button', {
        tooltip: '展开',
        text: '展',
        glyph: 0xf103,
        handler: function () {
            theGrid.collapseGroupsToLevel(4);
        }
    });
    //收缩
    let btnShrink = Ext.create('Ext.Button', {
        tooltip: '收缩',
        text: '收',
        glyph: 0xf102,
        handler: function () {
            theGrid.collapseGroupsToLevel(1);
        }
    });
    //批量修改
    let btnBatchEdit = Ext.create('Ext.Button', {
        tooltip: '批量修改',
        text: '批',
        glyph: 0xf044,
        handler: function () {
            let source = theGrid.itemsSource.items;
            let ary1 = [];
            let pid = theGrid.selectedItems[0].ParentID;
            foreach(WorkShopLine, function (el) {
                if (el.Parent_ID == pid) {
                    let obj = new Object();
                    obj.value = el.Description;
                    obj.text = el.Description;
                    ary1.push(obj);
                }
            });
            let resourceCombox = Ext.create('Ext.form.ComboBox', {
                fieldLabel: '产线',
                store: Ext.create('Ext.data.Store', {
                    fields: ['value', 'text'],
                    data: ary1
                }),
                queryMode: 'local',
                displayField: 'text',
                valueField: 'value',
            });

            var txtDate = new Ext.form.DateField({
                fieldLabel: '日期',
                editable: false, //不允许对日期进行编辑  
                anchor: '100%',
                format: "Y-m-d",
                value: new Date()
            })
            var BatchEdit_wind = Ext.create('Ext.window.Window', {
                title: '批量修改',
                width: 500,
                height: 400,
                modal: true,
                items: [{
                    xtype: 'panel',
                    layout: 'form',
                    items: [resourceCombox, txtDate]
                }
                ],
                fbar: [
                    {
                        type: 'button',
                        text: '确定',
                        glyph: 0xf0c7,
                        handler: function () {
                            let rows = theGrid.getSelectItems();
                            for (let index = 0; index < rows.length; index++) {
                                const element = rows[index];
                                source.filter(function (p) {
                                    if (p.Number == element.Number) {
                                        p.Resource = resourceCombox.getValue();
                                        p.Date = txtDate.getValue();
                                        p.Resource_index = 99
                                    }
                                    return p;
                                });
                                theGrid.collectionView.refresh();
                            }
                            console.log(rows);
                            BatchEdit_wind.close();
                        }
                    },
                    {
                        type: 'button',
                        text: '取消',
                        glyph: 0xf410,
                        handler: function () {
                            BatchEdit_wind.close();
                        }
                    }
                ]
            });
            BatchEdit_wind.show();
        }
    });
    var tool = [
        btnReadOldPlan, btnReadNowPlan, btnNotFinishProductionOrder, btnBundleAnalysis,
        btnViewGdItemShortage, btnViewGdListShortage, btnAutomaticSorting, btnMoveUpward, btnMoveDown, btnSave,
        btnVirtualTicketEdit, btnVirtualTicketRead, btnExpansion, btnShrink, btnBatchEdit, '->', btnLockTicket,
        btnViewOverview, btnExportExcel, btnDelete, btnInitializationData, btnRefreshData
    ];
    return {
        xtype: 'panel',
        layout: 'border',
        tbar: tool,
        items: [
            {
                region: 'center',
                xtype: 'component',
                height: '100%',
                id: id,
                border: false,
                title: false,
                onRender: function () {
                },
                afterRender: function () {
                }
            }
        ]
    };
}